<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/2/28
 * Time: 19:40
 */

namespace app\common\model;


use app\common\cachemodel\AppConfig;
use app\common\lib\Util;
use think\Cache;

/**
 * 教学课程相关模型
 * Class ZhunleCourse
 * @package app\common\model
 */
class ZhunleCourse extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_course';

    const ALL_COURSE_IDS = 'course:ids';//课程id缓存键名
    const COURSE_INFO_GID = 'course:info:gid:';//课程基本信息缓存键名
    const COURSE_INFO_ID = 'course:info:id:';//课程基本信息缓存键名
    const COURSE_INTRODUCTION = 'course:introduction:';//课程简介缓存键名
    const CACHE_TIME = 86400 * 7;


    /**
     * 获取所有上架的课程基本信息(分页)
     * @param array $map
     * @return array|bool
     */
    public function getAllCourseInfo($map = [])
    {
        $page = $map['page'];

        $all_course_ids = false;

        if ($this->cache_on >= 1)
        {
            $all_course_ids = Cache::get(self::ALL_COURSE_IDS);
        }

        // 获取所有课程id
        if ($all_course_ids === false)
        {
            try
            {
                $data = $this
                    ->where('status', 1)
                    ->order('sort DESC,create_time ASC')
                    ->column('id');

                // 将课程id组成字符串
                if (!empty($data))
                {
                    $all_course_ids = implode(',', $data);
                }

                // 缓存课程id,根据课程id
                if ($all_course_ids && $this->cache_on >= 1)
                {
                    Cache::set(self::ALL_COURSE_IDS, $all_course_ids, self::CACHE_TIME);
                }

            }
            catch (\Exception $e)
            {
                $this->error = '获取上架的课程基本信息失败';

                return false;
            }

        }
        // 将课程id转为数组
        $all_course_ids = explode(',', $all_course_ids);

        $per_page = 10;// 当前文章评论每页显示数量

        // 统计有多少课程
        $total = count($all_course_ids);
        //获取数据分页信息
        $data_list = getPaginatorData($total, $page, $per_page);

        //获取分页后的课程id数组
        $all_course_id = array_slice($all_course_ids, $data_list['start'], $per_page);

        unset($data_list['start']);
        unset($data_list['end']);


        // 根据当前页课程id获取所需的课程信息
        if (!empty($all_course_id))
        {
            $ac_ids = '';
            $temp = [];

            // 从缓存课程内容,根据课程id
            foreach ($all_course_id as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据课程id 获取课程内容
                    $temp[$ac_id] = Cache::get(self::COURSE_INFO_ID . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 课程内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false && $ac_id)
                {
                    $ac_ids .= ',' . $ac_id;
                }
            }

            // 从数据库获取课程内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                // 去掉开头的,
                $ac_ids = substr($ac_ids, 1);
                try
                {
                    $course = $this->alias('c')
                        ->field('c.id,c.is_recommended,c.title,c.thumb,c.video_thumb,c.description,c.base_num,g.id gid,g.or_prize,g.now_prize')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'c.gid=g.id', 'INNER')
//                        ->join('wechat_backup_07_18_14_43_00.zhunle_goods_commodity_attr gcr','c.gcrid=gcr.id','INNER')
                        ->where('c.status', 1)
                        ->where('c.id in(' . $ac_ids . ')')
                        ->order('c.sort DESC,c.create_time ASC')
                        ->select();

                    $course = json_decode(json_encode($course, true), true);

                }
                catch (\Exception $e)
                {
                    $this->error = '获取课程基本信息失败';
                    return false;
                }

                if (!empty($course))
                {
                    foreach ($course as $c)
                    {
                        // 将课程内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set(self::COURSE_INFO_ID . $c['id'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        if ($c)
                        {
                            $temp[$c['id']] = $c;
                        }
                    }
                }
            }

            foreach ($temp as $item)
            {
                if ($item)
                {
                    $data_list['data'][] = $item;
                }
            }
        }

        return $data_list;
    }

    /**
     * 获取某一个课程基本信息
     * @param array $map
     * @return array|bool
     */
    public function getCourseInfo($map = [])
    {

        $gid = $map['gid'] ?? 0;
        $id = $map['id'] ?? 0;

        $data = false;

        if ($gid)
        {
            $cachename = self::COURSE_INFO_GID;
            $where = ['c.status' => 1, 'c.gid' => $gid];
            if ($this->cache_on >= 1)
            {
                // 根据课程id 获取课程内容
                $data = Cache::get($cachename . $gid);
            }
        } else
        {
            $cachename = self::COURSE_INFO_ID;
            $where = ['c.status' => 1, 'c.id' => $id];
            if ($this->cache_on >= 1)
            {
                // 根据课程id 获取课程内容
                $data = Cache::get($cachename . $id);
            }
        }

        // 从数据库获取课程内容
        if ($data === false)
        {

            try
            {
                $data = $this
                    ->alias('c')
                    ->field('c.id,c.is_recommended,c.title,thumb,c.video_thumb,c.description,c.base_num,g.id gid,g.or_prize,g.now_prize')
                    ->join('wechat_backup_07_18_14_43_00.app_goods g', 'c.gid=g.id', 'inner')
//                    ->join('wechat_backup_07_18_14_43_00.zhunle_goods_commodity_attr gcr','c.gcrid=gcr.id','inner')
                    ->where($where)
                    ->order('c.sort DESC,c.create_time ASC')
                    ->find();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
                $this->error = '获取课程基本信息失败';
                return false;
            }

            if (!empty($data))
            {
                // 将课程内容缓存
                if ($this->cache_on >= 1)
                {
                    Cache::set($cachename . $id, $data, self::CACHE_TIME);
                }
            }
        }

        return $data;

    }

    /**
     * 获取某一个课程的简介（图文详情）
     * @param array $map
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getCourseIntroduction($map = [])
    {
        $id = $map['id'];

        $data = false;

        if ($this->cache_on >= 1)
        {
            // 根据课程id 获取课程内容
            $data = Cache::get(self::COURSE_INTRODUCTION . $id);
        }

        // 从数据库获取课程内容
        if ($data === false)
        {
            try
            {
                $data = $this
                    ->field('introduction')
                    ->where('status', 1)
                    ->where('id', $id)
                    ->order('sort DESC,create_time ASC')
                    ->find();
                $data = json_decode(json_encode($data, true), true);
            }
            catch (\Exception $e)
            {
                $this->error = '获取课程详情介绍失败。';
                return false;
            }

            if (!empty($data))
            {
                // 将课程内容缓存
                if ($this->cache_on >= 1)
                {
                    Cache::set(self::COURSE_INTRODUCTION . $id, $data, self::CACHE_TIME);
                }
            }
        }

        return $data;
    }

    /**
     * 获取课程限时免费剩余时间(秒)
     * @return array
     * @throws \Exception
     */
    public function getCourseTimeLimit($id)
    {
        $nowTime = time();
        $config = (new AppConfig())->configInfo('video_limit');
        $timeLimitInfo = isset($config[$id]) ? json_decode(htmlspecialchars_decode($config[$id]), true) : [];
        if ($timeLimitInfo && $nowTime > $timeLimitInfo['start_time'] && $nowTime < $timeLimitInfo['end_time'])
        {
            $timeDes = (new Util)->timediff($timeLimitInfo['end_time'], $nowTime);
            $des = '限时免费：';
            if ($timeDes['day'])
            {
                $des .= $timeDes['day'] . '天';
            }
            if ($timeDes['hour'])
            {
                $des .= $timeDes['hour'] . '小时';
            }
            $des .= '后结束';
            return [
                'time' => $timeLimitInfo['end_time'] - $nowTime,
                'des' => $des,
            ];
        }
        return [];
    }
}
